package com.zhiyou100.crm.servlet.user;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.zhiyou100.crm.pojo.AdminBaseServlet;
import com.zhiyou100.crm.pojo.Pager;
import com.zhiyou100.crm.pojo.User;
import com.zhiyou100.crm.service.UserService;
import com.zhiyou100.crm.service.impl.UserServiceImpl;

/**
 * 用户列表
 */
@WebServlet("/user/list")
public class ListServlet extends AdminBaseServlet {
	private static final long serialVersionUID = 1L;
	
	UserService userService = new UserServiceImpl();

       
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		List<User> users=new ArrayList<User>();
		users=userService.queryAllUser();
		if(users!=null) {
			//分页显示
			//初始页码
			int start = 1;
			int pageNo=1;
			//页面大小，设置
			int pageSize = 3;
			//获取当前页码
			String currentPage1 = request.getParameter("pageNo");
			if (currentPage1 != null) {
				int currentPage2 = Integer.parseInt(currentPage1);
				pageNo = currentPage2;
			}
			//总数据数，集合的大小
			int total = users.size();
			//总页数
			int pageCount = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
			Pager pager = new Pager(total,pageNo,pageSize,pageCount,start);
			List<User> users1 = new ArrayList<>();
			for (int i = (pageNo - 1) * pageSize; i < pageNo * pageSize; i++) {
				if (i == users.size()) {
					break;
				}
				users1.add(users.get(i));
			}
//			request.setAttribute("users", users);
			request.setAttribute("pager", pager);
			request.setAttribute("users", users1);
			request.getRequestDispatcher("/WEB-INF/view/user/list.jsp").forward(request, response);
		}else {
			response.sendRedirect(request.getContextPath()+"/list.jsp");
		}
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		//类别
		String searchField = request.getParameter("searchField");
		String keyword = request.getParameter("keyword");
		User user=new User(searchField,keyword);
		List<User> users=userService.queryUserByName(user);
		request.setAttribute("users",users);
		request.getRequestDispatcher("/WEB-INF/view/user/list.jsp").forward(request, response);
	}

}
